<template>
  <div class="mypwd">
    <el-form
      :model="mypwdUser"
      status-icon
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="mypwdForm"
    >
      <!-- <el-form-item label="手机号" prop="telephone" ref='telephone'>
        <el-input v-model="mypwdUser.telephone"></el-input>
      </el-form-item> -->
      <el-form-item label="密码" prop="userPassword1">
        <el-input  type="password"  v-model="mypwdUser.userPassword1"></el-input>
      </el-form-item>
            <el-form-item label="确认密码" prop="userPassword">
        <el-input type="password" v-model="mypwdUser.userPassword"></el-input>
      </el-form-item>
       <el-form-item label="新密码" prop="userPassword2">
        <el-input type="password" v-model="mypwdUser.userPassword2"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "mypwd",
  data:function(){
    //自定义验证表单元素的方法
     var validatePass2 = (rule, value, callback) => {
         console.log(value)
        if (value !== this.mypwdUser.userPassword1) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
    return {
      mypwdUser:{
        userPassword1:'',
        userPassword2:'',
      },
      rules: {
          userPassword1: [
            {required:true,message:'密码不能为空', trigger: 'blur' },
            {min:6,max:6,message:'密码必须是6位',trigger:'blur'}
          ],
           userPassword: [
            {required:true,message:'确认密码不能为空', trigger: 'blur' },
             { validator: validatePass2, trigger: 'blur' }
          ],
          userPassword2: [
            {required:true,message:'新密码不能为空', trigger: 'blur' },
             {min:6,max:6,message:'新密码必须是6位',trigger:'blur'}
          ],
        }
    }
  },
  methods:{
    submitForm(formName) {
      //通过ref定位到form表单
        this.$refs[formName].validate((valid) => {
          if (valid) {
            alert('修改成功!');
            this.$axios.put('http://localhost:3000/users/userpassword',this.mypwdUser)
            .then(res => {
              console.log('成功！',res)
              this.$router.push('/login') //路由转向登录组件
            })
            .catch(err =>{
              console.log(err)
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        //实现重置表单元素数据
        this.$refs[formName].resetFields();
      }
  }
};
</script>
<style lang="css" scoped>

.mypwdForm{
  width: 400px;
  height: 380px;
  position:absolute;
  left:25%;
  top:30%;
  margin-left:100px;
  margin-top:-40px;
  border-radius: 5px;
  /* background-color: #ff9; */
  padding:20px 50px 10px 10px;
}
</style>